import ls from '@/lib/ls'
import { showToast } from 'vant';
/**
 * 项目API错误
 */
export class ApiError extends Error {
  constructor(code = 0, ...params) {
    super(...params)
    if (typeof Error.captureStackTrace === 'function') {
      Error.captureStackTrace(this, ApiError);
    }
    this.name = 'ApiError'
    this.code = code
    this.date = new Date()
  }

  solve() {
    const { code } = this
    this.prompt()
    // token鉴权失败
    if (code === 401 ) {
      setTimeout(function() {
        ls.remove('TOKEN')
        let path  = import.meta.env.VITE_PATH
        // window.location.href = '/mb/login'
        if(path){
            window.location.href = '/' + path + '/login' 
        }else{
          showToast('登录过期,请重新登录')
          setTimeout(() => {
            window.location.href = '/login'  
          }, 1500);
          
        }
        
      }, 1000)
    }
  }

  prompt() {
    const { message } = this
    showToast({
      message,
      ['z-index']: 3000,
    })
    console.log("错误信息",message)
  }
}

export class PublicJS {
  constructor() {
    this.Data = {
      Head: {},
      Content: { ObjectList: { UseTS: false, Object: [] } }
    };
  }

  initHead(head = {}) {
    const ui = ls.get('USER_INFO');
    const mergedHead = {
      MsgType: "query",
      UserCode: ui.userCode||"",
      UserName: ui.userName||"",
      OrgCode: ui.orgCode||"",
      OrgName: ui.orgName||"",
      SessionId: ui.sessionid||"",
      Token: ui.token||"",
      TakeDataType: "local",
      RemoteOrgCode: "",
      NoSync: false,
      IsTrace: false,
      ...head,
    }
    this.Data.Head = mergedHead;
  }

  entitydata() {
    return this.Data;
  }

  entityobj(...objects) {
    for (const obj of objects) {
      const {
        objectName,
        orgCode,
        attrList,
        doType = "",
        doTypeDescribe = "",
        useDistinct = "",
        useBackUp = "",
        useGroup = "",
        valueList = {},
        queryList = {},
        orderList = {},
        groupList = {},
        pageSize = "",
        pageIndex = "",
        subObjectList = {}
      } = obj;

      const entityObj = {
        AttrList: Object.assign({
          Name: objectName,
          OrgCode: orgCode,
          ...attrList
        }),
        ValueList: valueList,
        ...(Object.keys(queryList).length > 0 && { QueryList: queryList }),
        ...(Object.keys(orderList).length > 0 && { OrderList: orderList }),
        ...(Object.keys(groupList).length > 0 && { GroupList: groupList }),
        ...(pageSize !== "" && { PageSize: pageSize }),
        ...(pageIndex !== "" && { PageIndex: pageIndex }),
        ...(useGroup !== "" && { UseGroup: useGroup }),
        ...(Object.keys(subObjectList).length > 0 && { SubObjectList: subObjectList })
      };

      this.Data.Content.ObjectList.Object.push(entityObj);
    }
  }
}

